import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useContext, useEffect, useMemo, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { DescriptionsType } from '@/components/DescriptionsType';
import { getCompanyID, getLoadMapList, getPosIDs, getTenantID, getUserDepID, getUserDutyDepID, getUserID } from '@/utils';
import { getUpdateConfig } from '../mconfig/UpdateConfig';
import { connect, history } from 'umi';
import { Col, Form, Row, Spin, message, Tabs, Button, Space, Modal } from 'antd';
import { CheckCircleOutlined, CloseCircleOutlined, SaveOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { ILoadMapTypeAll, formatDecimal } from '@/common';
import '../common/style.less';
import { combinationAssetManageService } from '../services';
import { OpenAssetModal } from '../mconfig/OpenAssetModal';
import { IAssetListActionEnum, useAssetListManageReducer } from '../mconfig/useManageReducer';
import { AssetListManageContext } from '../mconfig';
import { getDetailService } from '../services/UpdateService';
import moment from 'moment';

const AcceptUpdateView: React.FC<any> = ({ curRes, locationProps }) => {
  /** 引入上下文 */
  const { selectAssetList, addAssetList, assetListDispatch } = useAssetListManageReducer();
  /** 样式根目录 */
  const { prefixCls, styleFixCls, assetForm } = useContext(AssetListManageContext);

  /** 详情数据 */
  const [detailInfo, setDetailInfo] = useState<any>({});

  /** 打开选择资产列表 */
  const [openAssetModal, setOpenAssetModal] = useState<boolean>(false);

  /** 组合表单下拉框初始化数据 */
  const [combinationFormData, setCombinationFormData] = useState<Record<string, any>>({
    assetClass: `${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}1007`,
    assetCode: `ZHBH${moment().format('YYYYMMDD')}`,
    sourceType: `${getTenantID()}${ILoadMapTypeAll.ASSET_SOURCE_TYPE}1003`,
    assetType: `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}1011`,
    assetClassCode: 'A09000000',
    useDepartmentID: getUserDepID(),
    userID: getUserID(),
  });

  /** 选择的单位id */
  const [companyId, setCompanyId] = useState<string>('');

  /** 改变选中的单位id */
  const changeCompanyId = (id: string) => {
    setCompanyId(id);
  };

  /** 获取详情回调 */
  const updataGetDetail = (res: any) => {
    if (res && res?.msgFlag) {
      /** 详情数据 */
      setDetailInfo(res?.obj);
      /** 回填详情数据 */
      config.form.setFieldsValue({
        ...res?.obj,
      });
      setCompanyId(res?.obj?.useCompanyID);
      assetListDispatch({
        type: IAssetListActionEnum.SELECT_ASSET,
        payload: res?.obj?.massetInfoList,
      });
    }
  };

  /** 获取入库详情 */
  const { getDetailLoading, getDetailRun } = getDetailService(updataGetDetail);

  /** 选择材料弹窗 */
  const openAssetModalStatus = () => {
    setOpenAssetModal(true);
  };

  /** 组合接口回调 */
  const combinationAssetManageCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      history.push({
        pathname: '/assetController/manage',
        state: {
          delRouterNameSource: history.location.pathname,
        },
      });
    } else {
      message.error(res?.msg);
    }
  };

  const { combinationAssetManageRun, combinationAssetManageLoading } = combinationAssetManageService(combinationAssetManageCallback);

  /** 设定主资产 */
  const setMainAsset = (checked: boolean, record: Record<string, any>, index: number) => {
    // if (checked) {
    //   let idx = selectModalList.findIndex((item: Record<string, any>) => {
    //     return item.isState === checked;
    //   });
    //   if (idx !== -1) {
    //     message.error('只能设置一个资产为主资产！');
    //   } else {
    //     selectModalList[idx].isState = true;
    //   }
    // } else {
    //   selectModalList[index].isState = false;
    // }
    // setSelectModalList([...selectModalList]);
  };

  /** 获取表单配置
   *  @pageType  传递的类型，是修改还是查看
   *  @record   当前项
   */
  const { config, methods } = getUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: locationProps?.state?.pageType === 'add' ? combinationFormData : detailInfo ? detailInfo : {},
    curRes,
    setMainAsset,
    openAssetModalStatus,
    changeCompanyId,
  });

  // 组合按钮
  const handleSave = () => {
    // 对表单进行校验，获取表单数据
    config.form.validateFields()?.then((values: any) => {
      delete values.assetOldPrice;
      if (selectAssetList.length <= 1) {
        message.error('请至少选择两个或两个以上的资产！');
        return;
      }
      if (locationProps?.state?.pageType === 'edit') {
        values = { ...detailInfo, ...values };
      } else {
        values.useCompanyID = getCompanyID();
        values.usePositionID = getUserDutyDepID();
        values = { ...combinationFormData, ...values };
      }
      // values.useCompanyID = companyId;
      let arr: any = [];
      for (let i = 0; i < selectAssetList.length; i++) {
        arr.push(selectAssetList[i].id);
      }
      values.resultantAssetIdList = arr;
      combinationAssetManageRun(values);
    });
  };

  /** 申请页ref */
  const { confirm } = Modal;

  /** 关闭当前页 */
  const handleClose = () => {
    confirm({
      title: '关闭',
      icon: <QuestionCircleOutlined />,
      content: '确定要关闭当前页吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        history.push({
          pathname: locationProps?.state?.returnPathName,
          state: {
            delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
            returnPathName: locationProps?.state?.returnPathName,
          },
        });
      },
      onCancel() {},
    });
  };

  /** 返回tab子页面 */
  const tabsItem = () => {
    let items: any[] = [
      {
        label: '资产组合',
        key: '001',
        children: (
          <>
            <div className="commonTabsBodyDom">
              <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
                <ScrollBarLayout style={{ padding: '5px 20px' }}>
                  <DescriptionsType config={config} />
                </ScrollBarLayout>
              </div>

              <div className="tabsBodyBottomBtn">
                <Space>
                  {locationProps?.state?.pageType !== 'detail' && (
                    <Button
                      type={'primary'}
                      // icon={<SaveOutlined />}
                      loading={combinationAssetManageLoading}
                      onClick={handleSave}
                    >
                      保存
                    </Button>
                  )}
                  <Button danger onClick={handleClose}>
                    关闭
                  </Button>
                </Space>
              </div>
            </div>
          </>
        ),
      },
    ];
    return items;
  };

  /** 监听修改参考价值 */
  useEffect(() => {
    let total: number = 0;
    for (let i = 0; i < selectAssetList.length; i++) {
      total += Number(selectAssetList[i].quantityOrArea) * Number(selectAssetList[i].assetValue);
    }
    total = Number(formatDecimal(total));
    config.form.setFieldValue('assetValue', total);
  }, [selectAssetList]);

  useEffect(() => {
    if (locationProps?.state?.pageType === 'add') {
      // 获取选中的列表
      // assetListDispatch({
      //   type: IAssetListActionEnum.SELECT_ASSET,
      //   payload: locationProps?.state?.selectRowKeys?.valList ? locationProps?.state?.selectRowKeys?.valList : [],
      // });
    } else {
      if (locationProps?.state?.id) {
        getDetailRun(locationProps?.state?.id);
      }
    }
  }, []);

  return (
    <>
      <AssetListManageContext.Provider
        value={{
          prefixCls,
          styleFixCls,
          addAssetList,
          selectAssetList,
          curRes,
          assetForm,
          assetListDispatch,
        }}
      >
        <div className={'apply-update-UpdataIntentBox'}>
          <Spin spinning={combinationAssetManageLoading || getDetailLoading}>
            <Row className={`${styleFixCls}row`}>
              <Col span={24} className={`${styleFixCls}row-col`}>
                <Tabs className={pageStyles['commonTabs']} type="card" onChange={(activeKey: string) => {}} items={tabsItem()} destroyInactiveTabPane={true} />
              </Col>
            </Row>
          </Spin>
          {/* 选择材料列表 */}
          {openAssetModal && (
            <OpenAssetModal
              curRes={curRes}
              isShowModal={openAssetModal}
              onClose={() => {
                setOpenAssetModal(false);
              }}
            />
          )}
        </div>
      </AssetListManageContext.Provider>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(AcceptUpdateView);
